﻿#region DaReportAudit
/*----------------------------------------------------------------
// 文件名：DaReportAudit.cs
// 功能描述：类ReportAudit的数据访问层
//
// 
// 创建时间：2009-05-19 DtataAccess template . Ver 4.0.20090408
//
// 修改标识： 
// 修改描述： 
//----------------------------------------------------------------*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Globalization;
using System.Text;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

using EQT.Model; 


namespace EQT.Dal
{
	///可以继承更上层接口,IReportAudit ,数据访问层基类DaBase，
	///DaBase中包含了DbException异常处理静态方法
    public	partial  class DaReportAudit:DaBase
    {	 
		#region SQL const
		internal const string TABLE_COLUMNS=" RA_ID ,REPORT_ID ,AUDITOR_ID ,FLOW_CODE ,BEGIN_STATUS ,END_STATUS ,AUDIT_TIME ,CREATE_TIME ,AUDIT_INFO   ";

        internal const string SQL_INSERT = "INSERT INTO REPORT_AUDIT (" + TABLE_COLUMNS + ") VALUES (@RaId,@ReportId,@AuditorId,@FlowCode,@BeginStatus,@EndStatus,getdate(),getdate(),@AuditInfo)";
		internal const string SQL_SELECT="SELECT "+TABLE_COLUMNS+" FROM REPORT_AUDIT  ";
		internal const string SQL_SELECT_ONE=SQL_SELECT+" WHERE RA_ID=@RaId";                              
		
		internal const string SQL_EXIST="SELECT COUNT(*) FROM REPORT_AUDIT  WHERE RA_ID=@RaId  ";
        internal const string SQL_UPDATE = "UPDATE REPORT_AUDIT SET REPORT_ID=@ReportId, AUDITOR_ID=@AuditorId, FLOW_CODE=@FlowCode, BEGIN_STATUS=@BeginStatus, END_STATUS=@EndStatus, AUDIT_TIME=getdate(), AUDIT_INFO=@AuditInfo WHERE RA_ID=@RaId";
		internal const string SQL_DELETE="DELETE FROM REPORT_AUDIT WHERE RA_ID=@RaId";
		internal const string SQL_COUNT="SELECT COUNT(*) FROM Report_Audit";
		#endregion
		
        private Database db;
		
		#region Constructor
	 
		/// <summary>
        /// 默认构造函数，使用配置文件中默认的数据库配置。
        /// </summary>
		public DaReportAudit ()
		{ 
			this.db=DatabaseFactory.CreateDatabase();
		}
		/// <summary>
        /// 使用指定的databaseName数据库配置。
        /// </summary>
        /// <param name="databaseName">配置文件中数据库的配置名称。</param>
		public DaReportAudit (string databaseName)
		{ 
            this.db = DatabaseFactory.CreateDatabase(databaseName);
		} 
		
		public DaReportAudit (Database db)
		{ 
            this.db = db;
		} 
		
		#endregion
		
		//以下是CRUD方法，每个方法都有引入外部事务的版本

	    
		
		#region static helper for Add
		///build the command object.It never throw exception.
		internal static  DbCommand ConstructAddCommand(Database db)
		{
			DbCommand dbCommand = db.GetSqlStringCommand(SQL_INSERT);
			 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString);
			db.AddInParameter(dbCommand,"ReportId",DbType.AnsiString);
			db.AddInParameter(dbCommand,"AuditorId",DbType.AnsiString);
			db.AddInParameter(dbCommand,"FlowCode",DbType.AnsiString);
			db.AddInParameter(dbCommand,"BeginStatus",DbType.Int32);
			db.AddInParameter(dbCommand,"EndStatus",DbType.Int32);
			
     
			db.AddInParameter(dbCommand,"AuditInfo",DbType.String);
			return dbCommand;
		}		
		internal static DbCommand ConstructAddCommand(Database db,MoReportAudit entity)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_INSERT);			 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
			db.AddInParameter(dbCommand,"ReportId",DbType.AnsiString,entity.ReportId);
			db.AddInParameter(dbCommand,"AuditorId",DbType.AnsiString,entity.AuditorId);
			db.AddInParameter(dbCommand,"FlowCode",DbType.AnsiString,entity.FlowCode);
			db.AddInParameter(dbCommand,"BeginStatus",DbType.Int32,entity.BeginStatus);
			db.AddInParameter(dbCommand,"EndStatus",DbType.Int32,entity.EndStatus);
			

			db.AddInParameter(dbCommand,"AuditInfo",DbType.String,entity.AuditInfo);
			return dbCommand;
		}
		
		internal static DbCommand PopulateAddCommandParameters(Database db,DbCommand addCmd,MoReportAudit entity)
		{
			db.SetParameterValue(addCmd,"RaId",entity.RaId);
			db.SetParameterValue(addCmd,"ReportId",entity.ReportId);
			db.SetParameterValue(addCmd,"AuditorId",entity.AuditorId);
			db.SetParameterValue(addCmd,"FlowCode",entity.FlowCode);
			db.SetParameterValue(addCmd,"BeginStatus",entity.BeginStatus);
			db.SetParameterValue(addCmd,"EndStatus",entity.EndStatus);
		
        
			db.SetParameterValue(addCmd,"AuditInfo",entity.AuditInfo);
			return addCmd;
		}
		
		internal static DbCommand PopulateAddCommandParameters(Database db,DbCommand addCmd,DataRow row)
		{
			db.SetParameterValue(addCmd,"RaId",row["RaId"]);
			db.SetParameterValue(addCmd,"ReportId",row["ReportId"]);
			db.SetParameterValue(addCmd,"AuditorId",row["AuditorId"]);
			db.SetParameterValue(addCmd,"FlowCode",row["FlowCode"]);
			db.SetParameterValue(addCmd,"BeginStatus",row["BeginStatus"]);
			db.SetParameterValue(addCmd,"EndStatus",row["EndStatus"]);
		
        
			db.SetParameterValue(addCmd,"AuditInfo",row["AuditInfo"]);
			return addCmd;
		}
		
		#endregion
		
	    #region Add
	    /// <summary>
		///在某事务下增加一条记录，事务没有commit
		/// </summary>
	    public int Add(MoReportAudit entity,DbTransaction trans)
	    {	
			if(entity==null) throw new ArgumentNullException("entity","Could not add null MoReportAudit.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			DbCommand dbCommand=ConstructAddCommand(db,entity);			
			try
            {				
				return db.ExecuteNonQuery(dbCommand,trans);
			}
			catch(DbException ex)
			{	
				HandleDbException(ex,entity);				
			}
			return 0;
			
	    }		
	    public int Add(MoReportAudit entity) 
        {	
			if(entity==null) throw new ArgumentNullException("entity","Could not add null MoReportAudit.");
			DbCommand dbCommand=ConstructAddCommand(db,entity);	
			try
            {						
				return db.ExecuteNonQuery(dbCommand);
			}
			catch(DbException ex)
			{				
				HandleDbException(ex,entity);		
			}
			return 0;
	    }
		
		public int Add(ReadOnlyCollection<MoReportAudit> entity,DbTransaction trans)
		{
			if(entity==null) throw new ArgumentNullException("entity","ReadOnlyCollection<MoReportAudit> Could not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			int rc=0;		
            DbCommand dbCommand=ConstructAddCommand(db);
			int j=0;
			try
			{
			   for(j=0;j<entity.Count;j++)
			   {	
				PopulateAddCommandParameters(db,dbCommand,entity[j]);
				rc+=db.ExecuteNonQuery(dbCommand,trans);
			   }
			}
			catch(DbException ex)
			{			
				HandleDbException(ex,entity[j]);	
				rc=0;
			}			 
            return rc;
		}		
		public int Add(ReadOnlyCollection<MoReportAudit> entity)
		{
			if(entity==null) throw new ArgumentNullException("entity","ReadOnlyCollection<MoReportAudit> Could not be null.");
				
			int rc = 0;			
			using (DbConnection cnn = db.CreateConnection())
            {    
				DbTransaction trans=null;
				try
				{
					cnn.Open();
					using(trans = cnn.BeginTransaction())
					{
						rc=Add(entity,trans);//This function throw customer exception.
						trans.Commit();
					}
					cnn.Close();
				}
				catch(DbException ex)
				{
					if(trans!=null)trans.Rollback();		
					HandleDbException(ex);	
					rc=0;
				}
			
			}
			return rc;
		}
		
        public int Add(DataTable dt, DbTransaction trans)
		{
			if(dt==null) throw new ArgumentNullException("dt","DataTable Could not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		
			int rc=0;		 
            DbCommand dbCommand =ConstructAddCommand(db);	
			int j=0;
			try
			{
			   for(j=0;j<dt.Rows.Count;j++)
			   {	
				   PopulateAddCommandParameters(db,dbCommand,dt.Rows[j]);
				   rc+=db.ExecuteNonQuery(dbCommand,trans);
			   }
			}
			catch(DbException ex)
			{	
				HandleDbException(ex,dt.Rows[j]);				
			}	
			 
            return rc;
		}		
		public int Add(DataTable dt)
        {
			if(dt==null) throw new ArgumentNullException("dt","DataTable Could not be null.");
			
			int rc=0;
            using (DbConnection cnn = db.CreateConnection())
            { 
				DbTransaction trans=null;
				try
                {
					cnn.Open();
					using(trans = cnn.BeginTransaction())
					{
						rc = Add(dt, trans);
						trans.Commit();
						cnn.Close();
					}
				}
				catch(DbException ex)
				{	
					if(trans!=null)trans.Rollback();
					HandleDbException(ex);	
					rc=0;
				}	
				
            }
            return rc;
        }
		#endregion
		
		#region Update
		#region helper
		internal static DbCommand ConstructUpdateCommand(Database db)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_UPDATE);		    
			db.AddInParameter(dbCommand,"ReportId",DbType.AnsiString);
			db.AddInParameter(dbCommand,"AuditorId",DbType.AnsiString);
			db.AddInParameter(dbCommand,"FlowCode",DbType.AnsiString);
			db.AddInParameter(dbCommand,"BeginStatus",DbType.Int32);
			db.AddInParameter(dbCommand,"EndStatus",DbType.Int32);
		
          
			db.AddInParameter(dbCommand,"AuditInfo",DbType.String);
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString);
			 
			return dbCommand;
		}
		internal static DbCommand ConstructUpdateCommand(Database db,MoReportAudit entity)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_UPDATE);		    
			db.AddInParameter(dbCommand,"ReportId",DbType.AnsiString,entity.ReportId);
			db.AddInParameter(dbCommand,"AuditorId",DbType.AnsiString,entity.AuditorId);
			db.AddInParameter(dbCommand,"FlowCode",DbType.AnsiString,entity.FlowCode);
			db.AddInParameter(dbCommand,"BeginStatus",DbType.Int32,entity.BeginStatus);
			db.AddInParameter(dbCommand,"EndStatus",DbType.Int32,entity.EndStatus);
		
         
			db.AddInParameter(dbCommand,"AuditInfo",DbType.String,entity.AuditInfo);
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
			 
			return dbCommand;
		}
		
		internal static DbCommand PopulateUpdateCommandParameters(Database db,DbCommand updateCmd,MoReportAudit entity)
		{
			db.SetParameterValue(updateCmd,"ReportId",entity.ReportId);
			db.SetParameterValue(updateCmd,"AuditorId",entity.AuditorId);
			db.SetParameterValue(updateCmd,"FlowCode",entity.FlowCode);
			db.SetParameterValue(updateCmd,"BeginStatus",entity.BeginStatus);
			db.SetParameterValue(updateCmd,"EndStatus",entity.EndStatus);
		
			db.SetParameterValue(updateCmd,"AuditInfo",entity.AuditInfo);
			db.SetParameterValue(updateCmd,"RaId",entity.RaId);
			return updateCmd;
		}
		internal static DbCommand PopulateUpdateCommandParameters(Database db,DbCommand updateCmd,DataRow row)
		{
			db.SetParameterValue(updateCmd,"ReportId",row["ReportId"]);
			db.SetParameterValue(updateCmd,"AuditorId",row["AuditorId"]);
			db.SetParameterValue(updateCmd,"FlowCode",row["FlowCode"]);
			db.SetParameterValue(updateCmd,"BeginStatus",row["BeginStatus"]);
			db.SetParameterValue(updateCmd,"EndStatus",row["EndStatus"]);
			
           
			db.SetParameterValue(updateCmd,"AuditInfo",row["AuditInfo"]);
			db.SetParameterValue(updateCmd,"RaId",row["RaId"]);
			return updateCmd;
		}
		#endregion
		/// <summary>
		/// 根据主键更新实体。注意:主键列本身并未更新。
		/// </summary>	
	    public int Update(MoReportAudit entity,DbTransaction trans)
	    {	
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit Could not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		    DbCommand dbCommand=ConstructUpdateCommand(db,entity);
			try
            {
				return db.ExecuteNonQuery(dbCommand,trans);
			}
			catch(DbException ex)
			{				
				HandleDbException(ex,entity);		
			}
			return 0;
		}		
		public int Update(MoReportAudit entity)
		{
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit Could not be null.");
	        DbCommand dbCommand=ConstructUpdateCommand(db,entity);
			try
            {	
				return db.ExecuteNonQuery(dbCommand);
			}
			catch(DbException ex)
			{				
				HandleDbException(ex,entity);		
			}
			return 0;			
		}		
		public int Update(ReadOnlyCollection<MoReportAudit> entity,DbTransaction trans)
		{
			if(entity==null) throw new ArgumentNullException("entity","ReadOnlyCollection<MoReportAudit> Could not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			
			int rc=0;int j=0;
			DbCommand dbCommand=ConstructUpdateCommand(db);
			try
			{
			    for(j=0;j<entity.Count;j++)
				{	
					PopulateUpdateCommandParameters(db,dbCommand,entity[j]);
					rc+=db.ExecuteNonQuery(dbCommand,trans);
				}
			}
			catch(DbException ex)
			{  				
				HandleDbException(ex,entity[j]);		
				rc=0;
			}			 
			return rc;			
		}		
		public int Update(ReadOnlyCollection<MoReportAudit> entity)
		{
			if(entity==null) throw new ArgumentNullException("entity","ReadOnlyCollection<MoReportAudit> Could not be null.");
			
			int rc = 0;	
			using (DbConnection cnn = db.CreateConnection())
            {   
				DbTransaction trans=null;
				try
				{          
					cnn.Open();
					using(trans = cnn.BeginTransaction())
					{
					rc=Update(entity,trans);
					trans.Commit();		
					}
					cnn.Close();
				}
				catch(DbException ex)
				{
					if(trans!=null)trans.Rollback();	
					HandleDbException(ex);	
				}				
			}
			return rc;
		}		
		public int Update(DataTable dt, DbTransaction trans)
		{
			if(dt==null ||dt.Rows.Count==0) return 0;			 
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		
			int rc=0;int j=0;			 
            DbCommand dbCommand=ConstructUpdateCommand(db);				
		    try
		    {
			    for(j=0;j<dt.Rows.Count;j++)
				{	
                    PopulateUpdateCommandParameters(db,dbCommand,dt.Rows[j]);
					rc+=db.ExecuteNonQuery(dbCommand,trans);
				}
			}
			catch(DbException ex)
			{	
				HandleDbException(ex,dt.Rows[j]);		
				rc=0;
			}		
            return rc;
			
		}		
		public int Update(DataTable dt)
        {
			if(dt==null ||dt.Rows.Count==0) return 0;
            int rc=0;       
            using (DbConnection cnn = db.CreateConnection())
            {
				DbTransaction trans=null;
				try
                {
					cnn.Open();
					using(trans = cnn.BeginTransaction())
					{
						rc = Update(dt, trans);
						trans.Commit();						
					}   
					cnn.Close();                  
                }				
                catch(DbException ex)
				{
					if(trans!=null)trans.Rollback();	
					HandleDbException(ex);	
					rc=0;
				}     
				
            }
            return rc;
        }
		#endregion
		
		#region Update By DataSet
		internal static void PrepareDataAdapterCommand(Database db,out DbCommand dbInsertCommand,
		                     out DbCommand dbUpdateCommand,out DbCommand dbDeleteCommand)
		{
			dbInsertCommand = db.GetSqlStringCommand(SQL_INSERT);
			#region set insert cmd parameters
			db.AddInParameter(dbInsertCommand, "RaId",DbType.AnsiString, "RA_ID", DataRowVersion.Current);
			db.AddInParameter(dbInsertCommand, "ReportId",DbType.AnsiString, "REPORT_ID", DataRowVersion.Current);
			db.AddInParameter(dbInsertCommand, "AuditorId",DbType.AnsiString, "AUDITOR_ID", DataRowVersion.Current);
			db.AddInParameter(dbInsertCommand, "FlowCode",DbType.AnsiString, "FLOW_CODE", DataRowVersion.Current);
			db.AddInParameter(dbInsertCommand, "BeginStatus",DbType.Int32, "BEGIN_STATUS", DataRowVersion.Current);
			db.AddInParameter(dbInsertCommand, "EndStatus",DbType.Int32, "END_STATUS", DataRowVersion.Current);
		
           
			db.AddInParameter(dbInsertCommand, "AuditInfo",DbType.String, "AUDIT_INFO", DataRowVersion.Current);
			#endregion
			dbUpdateCommand = db.GetSqlStringCommand(SQL_UPDATE);
			#region Set update cmd value parameters
			db.AddInParameter(dbUpdateCommand, "ReportId", DbType.AnsiString, "REPORT_ID", DataRowVersion.Current);
			db.AddInParameter(dbUpdateCommand, "AuditorId", DbType.AnsiString, "AUDITOR_ID", DataRowVersion.Current);
			db.AddInParameter(dbUpdateCommand, "FlowCode", DbType.AnsiString, "FLOW_CODE", DataRowVersion.Current);
			db.AddInParameter(dbUpdateCommand, "BeginStatus", DbType.Int32, "BEGIN_STATUS", DataRowVersion.Current);
			db.AddInParameter(dbUpdateCommand, "EndStatus", DbType.Int32, "END_STATUS", DataRowVersion.Current);
		
			
			db.AddInParameter(dbUpdateCommand, "AuditInfo", DbType.String, "AUDIT_INFO", DataRowVersion.Current);
			#endregion
			#region set update cmd pk where parameters
			db.AddInParameter(dbUpdateCommand, "RaId", DbType.AnsiString, "RA_ID", DataRowVersion.Current);
			#endregion			
			dbDeleteCommand = db.GetSqlStringCommand(SQL_DELETE);
			#region set delete cmd pk where parameters
			db.AddInParameter(dbDeleteCommand, "RaId", DbType.AnsiString, "RA_ID", DataRowVersion.Current);
			#endregion
		}
		
		
		
		/// <summary>
        /// 通过DataSet修改表数据
        /// </summary>
        /// <param name="dst">DataSet ,contain the all data.</param>
        /// <param name="strTableName">The taget table .</param>
        /// <param name="trans">The DbTransaction,could not be null.</param>
        /// <returns>how many rows to be modifid.</returns>
		public int UpdateByDataSet(DataSet dst, string strTableName, DbTransaction trans)
		{
			if(dst==null) throw new ArgumentNullException("dst","DataSet Could not be null.");			
		    if(String.IsNullOrEmpty(strTableName)) throw new ArgumentNullException("strTableName","The taget table name should not be null or blank.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			DbCommand dbInsertCommand = null;			
			DbCommand dbUpdateCommand = null;
			DbCommand dbDeleteCommand = null;
			PrepareDataAdapterCommand(db,out dbInsertCommand,out dbUpdateCommand,out dbDeleteCommand);
			try
            {
			    return db.UpdateDataSet(dst, strTableName, dbInsertCommand, dbUpdateCommand, dbDeleteCommand, trans);
			}
			catch(DbException ex)
			{			
				trans.Rollback();
				HandleDbException(ex);				
			}
			return -1;//TODO:Should return Application Specific Error Code.
		}
		
		/// <summary>
		/// 通过DataSet修改表数据（不带事务）
		/// </summary>
		public int UpdateByDataSet(DataSet dst, string strTableName)
		{
			if(dst==null) throw new ArgumentNullException("dst","DataSet Could not be null.");			 
		    if(String.IsNullOrEmpty(strTableName)) throw new ArgumentNullException("strTableName","The taget table name should not be null or blank.");
			
			DbCommand dbInsertCommand = null;			
			DbCommand dbUpdateCommand = null;
			DbCommand dbDeleteCommand = null;
			PrepareDataAdapterCommand(db,out dbInsertCommand,out dbUpdateCommand,out dbDeleteCommand);
			try
            {
			    return db.UpdateDataSet(dst, strTableName, dbInsertCommand, dbUpdateCommand, dbDeleteCommand, UpdateBehavior.Transactional);			
			}
			catch(DbException ex)
			{	
				HandleDbException(ex);				
			}
			return 0;//TODO:Should return Application Specific Error Code.			
		}
		
		
		
		#endregion 
		
		#region Delete
		#region helper
		internal static DbCommand ConstructDeleteCommand(Database db)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_DELETE);
			 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString);
			 
			return dbCommand;
		}		
		internal static DbCommand ConstructDeleteCommand(Database db,MoReportAudit entity)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_DELETE);
			 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
		 
			return dbCommand;
		}
		#endregion helper
		/// <summary>
		/// delete by pk(entity)
		/// </summary>	
		public int Delete(MoReportAudit entity,DbTransaction trans)
		{	
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit Could not be null.");			
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			DbCommand dbCommand=ConstructDeleteCommand(db,entity);	
			try
            {					
				return db.ExecuteNonQuery(dbCommand,trans);
			}
			catch(DbException ex)
			{			
				if(trans!=null)trans.Rollback();
				HandleDbException(ex,entity);				
			}
			return 0;
		}	
		public int Delete(MoReportAudit entity)
		{
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit Could not be null.");			
			DbCommand dbCommand=ConstructDeleteCommand(db,entity);		
			try
            {					
				return db.ExecuteNonQuery(dbCommand);
			}
			catch(DbException ex)
			{				
				HandleDbException(ex,entity);				
			}
			return 0;
		}		
		/// <summary>
		/// mul-delete
		/// </summary>	
		public int Delete(ReadOnlyCollection<MoReportAudit> entities,DbTransaction trans)
		{
			if(entities==null) throw new ArgumentNullException("entities","ReadOnlyCollection<MoReportAudit> Could not be null.");			
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		
			int rc=0;	
			int j=0;
			DbCommand dbCommand=ConstructDeleteCommand(db);		
			try
			{
			    for(j=0;j<entities.Count;j++)
				{	
					db.SetParameterValue(dbCommand,"RaId",entities[j].RaId);
					rc+=db.ExecuteNonQuery(dbCommand,trans);
				}
			}
			catch(DbException ex)
			{	
				if(trans!=null)trans.Rollback();
				HandleDbException(ex,entities[j]);		
				rc=0;
			}			 
			return rc;			
		}		
		public int Delete(ReadOnlyCollection<MoReportAudit> entities)
		{
			if(entities==null) throw new ArgumentNullException("entities","ReadOnlyCollection<MoReportAudit> Could not be null.");			
			
			int rc = 0;			
			using (DbConnection cnn = db.CreateConnection())
            {      
				DbTransaction trans=null;
				try
				{
					cnn.Open();
					using(trans = cnn.BeginTransaction())
					{
						rc=Delete(entities,trans);
						trans.Commit();
					}               
					cnn.Close();
				}
				catch(DbException ex)
				{	
					if(trans!=null)trans.Rollback();
					HandleDbException(ex);				
				}	
			}
			return rc;
		}
		
		/// <summary>
		/// delete via DataTable
		/// </summary>	
		public int Delete(DataTable dt,DbTransaction trans)
		{			
			if(dt==null ||dt.Rows.Count==0) return 0;			 
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		
			int rc=0;			
			int j=0;
			DbCommand dbCommand=ConstructDeleteCommand(db);		
			try
			{
			    for(j=0;j<dt.Rows.Count;j++)
				{	
					db.SetParameterValue(dbCommand,"RaId",dt.Rows[j]["RA_ID"]);
					rc+=db.ExecuteNonQuery(dbCommand,trans);
				}
			}
			catch(DbException ex)
			{	
				if(trans!=null)trans.Rollback();
				HandleDbException(ex,dt.Rows[j]);	
				rc=0;
			}			 
			return rc;			
		 	
		}		
		public int Delete(DataTable dt)
		{
			if(dt==null ||dt.Rows.Count==0) return 0;	
			int rc=0;
		    using (DbConnection cnn = db.CreateConnection())
            {
				DbTransaction trans=null;
				try
				{
					cnn.Open();				
					using(trans = cnn.BeginTransaction())
					{
						rc = Delete(dt,trans);
						trans.Commit();
					}
					cnn.Close();
                }
                catch(DbException ex)
				{	
					if(trans!=null)trans.Rollback();
					HandleDbException(ex);				
				}
                
            }
            return rc;
		}	
			
		/// <summary>
		/// delete via PK Filds.
		/// </summary>	
		public int DeleteByPK(string raId,DbTransaction trans)
		{		
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_DELETE);				 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,raId);
			try
			{				
				return db.ExecuteNonQuery(dbCommand,trans);
			}
			catch(DbException ex)
			{	
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}	
			return 0;
		}		
		public int DeleteByPK(string raId)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_DELETE);
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,raId);
			try
			{
				return db.ExecuteNonQuery(dbCommand);
			}
			catch(DbException ex)
			{			 
				HandleDbException(ex);				
			}	
			return -1;
		}
		
		public int DeleteByWhereClause(string where)
		{
			try
			{
			return db.ExecuteNonQuery(CommandType.Text,"DELETE FROM REPORT_AUDIT "+where);
			}
			catch(DbException ex)
			{			 
				HandleDbException(ex);				
			}	
			return -1;
			
		}
		
		public int DeleteByWhereClause(string where,DbTransaction trans)
		{			 
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			try
			{
				return db.ExecuteNonQuery(trans,CommandType.Text,"DELETE FROM REPORT_AUDIT "+where);
			}
			catch(DbException ex)
			{
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}	
			return -1;
		
		}
		
		#endregion
		
		#region Query All by condition
		/// <summary>
		/// 返回满足WHERE条件的记录的集合,若condition为空，则查询所有
		/// </summary>		
		public DataSet Query(string condition)
		{	
			try
			{
				return db.ExecuteDataSet(CommandType.Text,SQL_SELECT+condition);	 
			}
			catch(DbException ex)
			{			 
				HandleDbException(ex);				
			}            
			return null;
		}		
	    public DataSet Query(string condition,DbTransaction trans)
        {   
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_SELECT + condition);
            try
            {				
                return db.ExecuteDataSet(dbCommand,trans);
            }
            catch(DbException ex)
			{			
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}            
			return null;
        }
		#endregion
		
		#region GetEntity(s)
		/// <summary>
		///根据主键返回一个实体对象
		/// </summary>
	    public MoReportAudit GetEntity(string raId )
		{			 
			MoReportAudit entity = new MoReportAudit();
			entity.RaId=raId;
			if(GetEntityEx(ref entity))
			{
				return entity;
			}
			else
			{
				return null;
			}
		}
		
		public MoReportAudit GetEntity(string raId ,DbTransaction trans)
		{			
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
			MoReportAudit entity = new MoReportAudit();
			entity.RaId=raId;
			if(GetEntityEx(ref entity,trans))
			{
				return entity;
			}
			else
			{
				return null;
			}
		}
		#region internal help function
		internal static DbCommand ConstructSelectOneCommand(Database db,MoReportAudit entity)
		{
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_SELECT_ONE);
			 
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
			return dbCommand;
		}
		
		internal static void PopulateEntityByDataReader(IDataReader reader,ref MoReportAudit entity)
		{
			if (!reader.IsDBNull(0)) entity.RaId = reader.GetString(0);
			if (!reader.IsDBNull(1)) entity.ReportId = reader.GetString(1);
			if (!reader.IsDBNull(2)) entity.AuditorId = reader.GetString(2);
			if (!reader.IsDBNull(3)) entity.FlowCode = reader.GetString(3);
			if (!reader.IsDBNull(4)) entity.BeginStatus = reader.GetInt32(4);
			if (!reader.IsDBNull(5)) entity.EndStatus = reader.GetInt32(5);
			if (!reader.IsDBNull(6)) entity.AuditTime = reader.GetDateTime(6);
			if (!reader.IsDBNull(7)) entity.CreateTime = reader.GetDateTime(7);
			if (!reader.IsDBNull(8)) entity.AuditInfo = reader.GetString(8);
		}
		#endregion
		/// <summary>
		///实体的主键已经赋值。需要注意的是，实体应该中是一个类，而不是结构.
		///如果实体是结构，为了避免复制对象，应考虑使用ref关键字。
		/// </summary>
		public bool GetEntityEx(ref MoReportAudit entity)
		{
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit can not be null.");
			DbCommand dbCommand=ConstructSelectOneCommand(db,entity);
			try
			{
				using(IDataReader reader=db.ExecuteReader(dbCommand))
				{   
					if(reader.Read()) 
					{
						PopulateEntityByDataReader(reader,ref entity);
						return true;
					}
				}
			}
			catch(DbException ex)
			{	 
				HandleDbException(ex,entity);				
			}	
			return false;
		}
		public bool GetEntityEx(ref MoReportAudit entity,DbTransaction trans)
		{		
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit Could not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			DbCommand dbCommand=ConstructSelectOneCommand(db,entity);
			try
			{
				using(IDataReader reader=db.ExecuteReader(dbCommand,trans))
				{   
					if(reader.Read())
					{
						PopulateEntityByDataReader(reader,ref entity);	
						return true;
					}
				}
			} 
			catch(DbException ex)
			{			 
				if(trans!=null)trans.Rollback();
				HandleDbException(ex,entity);				
			}	
			return false;
			
		}
		
		public Collection<MoReportAudit> GetEntities(string condition,DbTransaction trans)
		{
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			Collection<MoReportAudit> list=new Collection<MoReportAudit>();			
			try
			{				
			    using(IDataReader reader= db.ExecuteReader(trans,CommandType.Text, String.IsNullOrEmpty(condition) ? SQL_SELECT : SQL_SELECT+ condition))
			    {
				    while(reader.Read())
					{			
						MoReportAudit entity=new MoReportAudit();
						PopulateEntityByDataReader(reader,ref entity);	
						list.Add(entity);
					}
			    }
			}
			catch(DbException ex)
			{			 
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}	
			return list;
			
		}
		
		
		public Collection<MoReportAudit> GetEntities(string condition)
		{
			Collection<MoReportAudit> list=new Collection<MoReportAudit>();	
			try
			{
				using(IDataReader reader= db.ExecuteReader(CommandType.Text, String.IsNullOrEmpty(condition) ? SQL_SELECT : SQL_SELECT+" " + condition))
				{   
					while(reader.Read())
					{	
						MoReportAudit entity=new MoReportAudit();
						PopulateEntityByDataReader(reader,ref entity);	
						list.Add(entity);
					}
				}
			}
			catch(DbException ex)
			{	 
				HandleDbException(ex);				
			}	
			return list;
		}
		#endregion
		
		#region Count
		/// <summary>
		/// 返回表的记录总数
		/// </summary>
		public int GetCount()
		{
			return Convert.ToInt32(db.ExecuteScalar(CommandType.Text,SQL_COUNT),CultureInfo.InvariantCulture);
		}
		
		public int GetCount(DbTransaction trans)
		{			 
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			try
			{
			    return Convert.ToInt32(db.ExecuteScalar(trans,CommandType.Text,SQL_COUNT),CultureInfo.InvariantCulture);
		    }
		    catch(DbException ex)
			{	 
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}	
			return -1;
		}
		
		/// <summary>
		/// 返回满足WHERE条件记录数
		/// </summary>
		public int GetCount(string where)
		{
			return Convert.ToInt32(db.ExecuteScalar(CommandType.Text,SQL_COUNT+where ),CultureInfo.InvariantCulture);
		}
		
		public int GetCount(string where,DbTransaction trans)
		{
			 if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			try
			{				
			   return Convert.ToInt32(db.ExecuteScalar(trans,CommandType.Text,SQL_COUNT+where ),CultureInfo.InvariantCulture);
		    }
			catch(DbException ex)
			{	 
				if(trans!=null)trans.Rollback();
				HandleDbException(ex);				
			}	
			return -1;
		}
		#endregion
		
		#region Check isExist
		/// <summary>
		/// 判断是否存在此主键的记录
		/// </summary>
        public bool IsExist(string raId )
		{				
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_EXIST);
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString, raId);
			try
			{
			return Convert.ToInt32(db.ExecuteScalar(dbCommand),CultureInfo.InvariantCulture)>0;
			}
			catch(DbException ex)
			{			     
				throw new DalException("Data Access Error:",ex);
			}
		}
		
		public bool IsExist(string raId ,DbTransaction trans)
		{	
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_EXIST);
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,raId);
			try
			{
			   return Convert.ToInt32(db.ExecuteScalar(dbCommand,trans),CultureInfo.InvariantCulture)>0;
			}
			catch(DbException ex)
			{
			    if(trans!=null)trans.Rollback();
				throw new DalException("Data Access Error:",ex);
			}	
			
		}
		
		public bool IsExist(MoReportAudit entity,DbTransaction trans)
		{	
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit can not be null.");
			if(trans==null) throw new ArgumentNullException("trans","DbTransaction can not be null.");
		  
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_EXIST);
			#region set pk where parameters
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
			#endregion
			try
			{
			   return Convert.ToInt32(db.ExecuteScalar(dbCommand,trans),CultureInfo.InvariantCulture)>0;
			}
			catch(DbException ex)
			{			  
				throw new DalException("Data Access Error:",ex);
			}		 
		}
		
		public bool IsExist(MoReportAudit entity)
		{			 
			if(entity==null) throw new ArgumentNullException("entity","MoReportAudit can not be null.");
			DbCommand dbCommand=db.GetSqlStringCommand(SQL_EXIST);
			#region set pk where parameters
			db.AddInParameter(dbCommand,"RaId",DbType.AnsiString,entity.RaId);
			#endregion
			try
			{
			    return Convert.ToInt32(db.ExecuteScalar(dbCommand),CultureInfo.InvariantCulture)>0;
			} 
			catch(DbException ex)
			{			     
				throw new DalException("Data Access Error:",ex);
			}
		}
		#endregion
		
		
	}
}	
#endregion

